const http = require('http')
const path = require('path')
const fs = require('fs')

const url = 'http://static.micheliafigo.xyz/books/1581347142049.jpeg'
const targetFile = path.join(__dirname, '../file/image.jpeg')
const reg = /(bytes)\s(\d+\-\d+)\/(\d+)/

// http.get(
//   url,
//   {
//     headers: {
//       Range: 'bytes=0-99999',
//       'If-Range': 'FF70503A7175D736D973ECE83554EE84'
//     }
//   },
//   function(response) {
//     let _buf
//     let chunk
//     response.on('data', function(chunk) {
//       // str += chunk //监听数据响应，拼接数据片段
//       chunk = Buffer.from(chunk)
//       if (!_buf) {
//         _buf = chunk
//       } else {
//         let _length = _buf.length + chunk.length
//         _buf = Buffer.concat([_buf, chunk])
//       }

//     })
//     response.on('end', function() {
//         this.buffer
//     })
//     let {
//       'content-length': contentType,
//       'content-range': contentRange,
//       'accept-ranges': acceptRanges
//     } = response.headers
//     console.log(contentType, contentRange, response.headers)
//     let allContentLength = contentRange.match(reg)[3]
//   }
// )

class Chunk {
  constructor() {
    this.contentLenght = 0
    this.range = 80000
    this.responseLength = 0
    this.bufferChunks = []
    this.allContentLength = 0
    this.start = false
    this.http(0)
  }

  responseChunk() {
    // console.log('start')
    for (let i = 1, length = this.readyBuffer(); i < length; i++) {
      // console.log('i', i)
      this.http(i, length - 1 === i)
    }
  }

  readyBuffer() {
    let chunkNumber = Math.floor(this.contentLenght / this.range)

    // 有余
    if (this.contentLenght % this.range) chunkNumber++

    return chunkNumber
  }

  http(index, isEnd) {
    let that = this
    let startRange = index * this.range
    let endRange = isEnd ? '' : (index + 1) * this.range - 1
    http.get(
      url,
      {
        headers: {
          Range: `bytes=${startRange}-${endRange}`,
          'If-Range': 'FF70503A7175D736D973ECE83554EE84'
        }
      },
      function(response) {
        let _buf
        let chunk
        //
        response.on('data', function(chunk) {
          // str += chunk //监听数据响应，拼接数据片段
          chunk = Buffer.from(chunk)
          if (!_buf) {
            _buf = chunk
          } else {
            let _length = _buf.length + chunk.length
            _buf = Buffer.concat([_buf, chunk])
          }
        })
        //
        response.on('end', function() {
          that.bufferChunks[index] = _buf
        })

        if (!that.start) {
          // static
          that.start = true
          //
          let {
            // 'content-length': contentType,
            'content-range': contentRange
            // 'accept-ranges': acceptRanges
          } = response.headers

          let r = contentRange.match(reg)
          that.contentLenght = r[3]
          //
          that.responseChunk()
        }
      }
    )
  }
}

let buf = new Chunk()
setTimeout(() => {
  console.log(buf.bufferChunks)
  wirteFile()
  // fs.open(targetFile, 'w', function(err, fd) {
  //   if (err) throw err
  //   fs.writeSync(fd, buf.bufferChunks[0], err => {
  //     err && console.log(err)
  //   })
  // })
}, 3000)

wirteFile = () => {
  let offset = 0
  // delete
  files = fs.existsSync(targetFile)
  files &&
    fs.unlinkSync(targetFile, function(err) {
      if (err) throw err
    })
  // write
  for (let bufItem of buf.bufferChunks) {
    let size = bufItem.length
    console.log(`size:${size}  offset:${offset}`)
    fs.open(targetFile, 'as+', function(err, fd) {
      if (err) throw err
      fs.writeSync(fd, bufItem, err => {
        err && console.log(err)
      })
    })
    offset += size
  }
}
